package util;

import Data.StoreDiskBlock;
import Data.StoreFileToDiskBlock;

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;

import static controller.MainController.*;

public class FileRW {
    public static void readDisk() throws IOException, ClassNotFoundException {
        Path currentPath = Paths.get("");
        String filePath = currentPath.toAbsolutePath() + "\\Disk.sfs";
        File file = new File(filePath);
        if(!file.exists()){
            file.createNewFile();
            rootFile = new Data.File(false, true, false, true, "c:", null);
        }else {
            try {
                ObjectInputStream oi = new ObjectInputStream(new FileInputStream(file));
                rootFile = (Data.File) oi.readObject();
                FileConvertToIcon fileConvertToIcon = new FileConvertToIcon();
                fileConvertToIcon.convert(rootFile);
                oi.close();
            } catch (EOFException e) {
                throw new RuntimeException(e);
            }
        }

        filePath = currentPath.toAbsolutePath()+"\\DiskBlock.sfs";
        file = new File(filePath);
        if(!file.exists()) {
            file.createNewFile();
        }else {
            try {
                ObjectInputStream bi = new ObjectInputStream(new FileInputStream(file));
                StoreDiskBlock[] t = (StoreDiskBlock[]) bi.readObject();
                StoreFileToDiskBlock d = new StoreFileToDiskBlock();
                d.setStoreDiskBlocks(t);
                d.convert(rootFile, fat.getDiskBlocks());
                bi.close();
            } catch (EOFException e) {
                System.out.println("没有文件读取");
            }
        }
    }

    public static void writeDisk() throws IOException, ClassNotFoundException {
        ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(new File("Disk.sfs")));

        oo.writeObject(rootFile);
        oo.close();
    }
}
